<template>
  <div class='custom-table-container'>
    <el-row>
      <el-form :model="filterParaForm"
               v-if="filterParamList.length>0"
               label-width="160px">
        <el-col :span="6">
          <el-form-item label="项目名称">
            <el-select v-model="requestParam.project_id"
                       @change="changeSel"
                       placeholder="请选择项目名称"
                       :disabled="selectedProArr.length === 1 ? true :false">
              <el-option v-for="item in selectedProArr"
                         :key="item.project_id"
                         :label="item.project_name"
                         :value="item.project_id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-for="item in filterParamList"
                :key="item.prop"
                :span="6">
          <el-form-item :label="item.label">
            <el-input v-model="item.value"
                      v-if="item.compType==='input'"
                      placeholder="请输入"></el-input>
            <el-select v-model="item.value"
                       v-if="item.compType==='select'"
                       placeholder="请选择">
              <el-option v-for="option in item.optionList"
                         :key="option.value"
                         :value="option.value"
                         :label="option.value"></el-option>
            </el-select>
            <!-- 时间控件-日期格式 -->
            <el-date-picker v-model="item.value"
                            :type="item.date_format==='yyyy-MM'?'monthrange':'daterange'"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :format="item.date_format"
                            :value-format="item.date_format"
                            v-if="item.compType==='date' && item.date_type==='date'"></el-date-picker>
            <!-- 时间控件-日期时间格式 -->
            <el-date-picker v-model="item.value"
                            type="datetimerange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :format="item.date_format"
                            :value-format="item.date_format"
                            v-if="item.compType==='date' && item.date_type==='datetime'"></el-date-picker>

            <!-- 时间控件-时间格式 -->
            <el-time-picker v-model="item.value"
                            is-range
                            range-separator="-"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :format="item.date_format"
                            :value-format="item.date_format"
                            v-if="item.compType==='date' && item.date_type==='time'"></el-time-picker>
          </el-form-item>
        </el-col>
        <el-col :offset="(filterParamList.length+1)%4===0?18:(3-(filterParamList.length+1)%4)*6"
                :span="6"
                class="flex-end">
          <el-button @click="search"
                     type="primary">查询
          </el-button>
          <el-button @click="reset">重置</el-button>
        </el-col>
      </el-form>
    </el-row>
    <el-row>
      <el-col :span="24"
              v-if="customTableDetail.opt_type.indexOf('3')>=0"
              class="export-btn flex-end">
        <el-button type="primary"
                   @click="batchPrint">批量打印
        </el-button>
        <!-- <el-button type="primary"
                   @click="batchExport">批量导出</el-button> -->
      </el-col>
    </el-row>
    <p v-if="customTableDetail.is_stat_by_where==='1'"
       class="stat-str">
      {{ statStr }}
    </p>
    <el-table :data="tableDataValue.list"
              ref="customTable"
              id="customTable"
              border
              :header-cell-style="{ background: '#f5f5f5' }"
              class="tabel-component">
      <!-- <el-table-column type="selection"></el-table-column> -->
      <el-table-column v-for="column in tableData"
                       :show-overflow-tooltip="true"
                       :align="column.align"
                       :key="column.name"
                       :width="column.width"
                       :prop="column.name"
                       :label="column.label">
        <template slot-scope="scope">
          <div :style="{'height':Number(customTableDetail.line_high)*30+'px',
          'lineHeight':Number(customTableDetail.line_high)*30+'px'}">
            <div v-if="column.name === 'gcyRzResult'"
                 class="gcyRzResult"
                 @click="gcyRzResultClick(scope.row[column.name])">
              二级认证
            </div>
            <span v-else>{{ scope.row[column.name] }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       v-if="customTableDetail.opt_type!==''">
        <template slot-scope="scope">
          <el-button type="text"
                     v-if="customTableDetail.opt_type.indexOf('1')>=0"
                     @click="checkDetail(scope.row)">查看
          </el-button>
          <el-button type="text"
                     @click="deleteItem(scope.row)"
                     v-if="customTableDetail.opt_type.indexOf('2')>=0">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @current-change="handlePageChange"
                   @size-change="handleSizeChange"
                   :current-page="requestParam.page"
                   :page-size="requestParam.page_size"
                   layout="total,sizes,prev, pager, next, jumper"
                   background
                   :total="tableDataValue.total_count"
                   align="center">
    </el-pagination>
    <!-- 模板列表弹框 -->
    <el-dialog title="选择打印模板"
               :visible.sync="dialogVisiblePrintFlag">
      <el-table ref="singleTable"
                :data="printTemplateList"
                highlight-current-row
                @current-change="handleCurrentChange"
                style="width: 100%">
        <el-table-column property="templete_name"
                         label="模板名称">
        </el-table-column>
      </el-table>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogVisiblePrintFlag = false">取 消</el-button>
        <el-button type="primary"
                   @click="toPrintPage">确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 导出及打印html模板 -->
    <el-table :data="choosedRow"
              style="display:none;"
              id="printTemplate"
              border
              :header-cell-style="{ background: '#f5f5f5' }"
              class="tabel-component">
      <el-table-column v-for="column in tableData"
                       :show-overflow-tooltip="true"
                       :align="column.align"
                       :key="column.name"
                       :width="column.width"
                       :prop="column.name"
                       :label="column.label">
        <template slot-scope="scope">
          <div :style="{'height':Number(customTableDetail.line_high)*30+'px',
          'lineHeight':Number(customTableDetail.line_high)*30+'px'}">
            {{ scope.row[column.name] }}
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { CustomTableApi } from '@/services/SystemSetting'
import { userPermissionApi } from "@/services/UserPermission";
import moment from 'moment'

export default {
  data () {
    return {
      id: '',
      requestParam: {
        check_tpl_id: '',
        orders: [],
        is_page: 1,
        page: 1,
        page_size: 10,
        injections: [],
        project_id: ''
      },
      // 筛选条件列表
      filterParamList: [],
      filterParaForm: {},
      tableDataValue: {
        list: [],
        total_count: 0
      },
      tableData: [],
      customTableDetail: {
        opt_type: ''
      },
      choosedProject: {},
      // 统计数据
      statStr: '',
      // 根据control_type使用不同的组件
      componentTypeMap: {
        '16': 'input',
        '17': 'input',
        '18': 'input',
        '19': 'date',
        '20': 'select',
        '21': 'select',
        '24': 'input',
        '28': 'input',
        '36': 'input'
      },
      // 时间格式
      dateFormat: {
        '1': 'yyyy-MM',
        '2': 'yyyy-MM-dd',
        '3': 'yyyy-MM-dd HH:mm',
        '4': 'yyyy-MM-dd HH:mm:ss',
        '5': 'HH:mm:ss',
      },
      // 日期控件格式
      dateType: {
        '1': 'date',
        '2': 'date',
        '3': 'datetime',
        '4': 'datetime',
        '5': 'time',
      },
      dialogVisiblePrintFlag: false,
      printTemplateList: [], // 打印弹窗的模版列表
      projectId: 0,
      // 选中的打印模板
      choosedTpl: {},
      // 选择的表格行
      choosedRow: [],
      userInfo: {},
      showGcyRzResult: false,
    }
  },
  watch: {
    '$store.state.choosedProject': function (val) {
      this.choosedProject = val
      this.requestParam.project_id = this.choosedProject.project_id
      this.project_id = val.project_id
      this.getCheckTplData()
    },
    $route (to, from) {
      this.id = this.$route.query.id
      this.getCustomTableDetail()
    },
    '$store.state.choosedProjectList': {
      handler (newval) {
        this.selectedProArr = newval.list
        if (this.selectedProArr.length !== 0) {
          this.formInline.project_id = this.selectedProArr[0].project_id
        }
      },
      deep: true
    },
    showGcyRzResult (val) {
      if (val) {
        this.tableData.push({
          "field": "gcyRzResult",
          "field_name": "工程云认证",
          "control_type": "22",
          "ais": null,
          "value": "工程云认证",
          "name": "gcyRzResult",
          "sort": 4,
          "align": "center",
          "isFilterParam": "0",
          "filterParamIndex": 4,
          "width": 0,
          "show": true,
          "label": "工程云认证"
        })
      }
    }
  },

  methods: {
    // 跳转到ureport页面
    toPrintPage () {
      let injections = []
      let param = JSON.parse(JSON.stringify(this.requestParam))
      let suffix = ''

      this.filterParamList.map((item) => {
        if (item.value) {
          // 时间类型时单独判断
          if (item.controlType === '19') {
            injections.push({
              key: item.key + '_start',
              value: item.value[0] || ''
            })
            injections.push({
              key: item.key + '_end',
              value: item.value[1] || ''
            })
          } else {
            injections.push({
              key: item.key,
              value: item.value
            })
          }

        }
      })
      param.page = 1
      param.injections = injections
      param.project_id = this.choosedProject.project_id
      param.company_id = this.userInfo.comp_id
      // suffix = 'json=' + encodeURI(JSON.stringify(param))
      suffix = `project_id=${this.choosedProject.project_id}&check_tpl_id=${this.requestParam.check_tpl_id}&is_page=1&page=${this.requestParam.page}&page_size=${this.requestParam.page_size}`
      let alink = document.createElement("a");
      alink.target = "_blank";
      let hrefUrl = `http://report.hibuilding.cn/ureport/preview?_u=file:${this.choosedTpl.categ_no}.ureport.xml&${suffix}`;
      alink.href = hrefUrl;
      alink.click();
      alink.remove();
    },
    handleCurrentChange (row) {
      this.choosedTpl = row
    },
    // 批量套打
    batchPrint () {
      this.choosedRow = this.$refs.customTable.selection
      userPermissionApi
        .printTemplateList({
          data: {
            templete_url: "custom-table-report",
            // company_id: this.companyId,
            // project_id: this.projectId
          }
        })
        .then(res => {
          if (res.code === 0) {
            this.dialogVisiblePrintFlag = true;
            this.printTemplateList = res.data;
          }
        });
    },
    // 批量导出
    batchExport () {
      let data = document.getElementById('customTable').innerHTML
      let fileType = 'application/vnd.ms-excel'
      let html = `
        <html>
          <head>
            <style>
              .h-table {
                width: 350mm;
                margin: 0 auto;
                padding: 20px
              }

              .el-table__header {
                border: 1px solid;
                width: 100%;
                font-size: 15px;
                text-align: center;
                border-collapse: collapse;
                table-layout: fixed
              }

              .el-table__header td,
              .el-table__header th {
                border-bottom: 1px solid #000 !important;
                border-right: 1px solid #000 !important;
                text-align: center;
                font-size: 14px;
              }

              .el-table__body {
                border-top: 1px solid;
                border-left: 1px solid;
                margin: 5px 2px 2px;
                table-layout: fixed;
                border-collapse: collapse;
                border-spacing: 0;
                width: calc(100% - 4px)
              }

              .el-table__body td,
              .el-table__body th {
                text-align: center
              }

              .table-bottom {
                margin: 10px 2px 2px;
                height: 150px;
                border: 1px solid #000 !important
              }

              .table-bottom .content {
                margin: 2px 10px 2px 2px;
                color: #999
              }
            </style>
          </head>
          <body>
            ${data}
          </body>
        </html>
      `
      let excelBlob = new Blob([html], {
        type: fileType
      });
      // 创建一个a标签
      let oA = document.createElement("a");
      // 利用URL.createObjectURL()方法为a元素生成blob URL
      oA.href = URL.createObjectURL(excelBlob);
      // 给文件命名
      oA.download = `自定义表格`;
      // 模拟点击
      oA.click();
    },
    deleteItem (row) {
      this.$confirm('是否删除? ', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        left: true
      }).then(() => {
        CustomTableApi.deleteCheckRecord({
          data: {
            check_record_id: row.check_record_id
          }
        }).then(res => {
          if (res.code === 0) {
            this.getCheckTplData()
          }
        })
      }).catch(() => {

      });

    },
    // 进入详情页
    checkDetail (row) {
      this.$router.push({
        path: "/customTableDetail",
        query: {
          id: row.check_record_id
        }
      });
    },
    changeSel (val) {
      this.getCheckTplData()
    },
    handleSizeChange (size) {
      this.requestParam.page_size = size
      this.requestParam.page = 1
      this.getCheckTplData()
    },
    handlePageChange (page) {
      this.requestParam.page = page
      this.getCheckTplData()
    },
    reset () {
      this.filterParamList.map((item) => {
        item.value = ''
      })
      this.requestParam.injections = []
      this.requestParam.page = 1
      this.requestParam.project_id = this.choosedProject.project_id
      this.getCheckTplData()
    },
    search () {
      let injections = []
      this.filterParamList.map((item) => {
        if (item.value) {
          // 时间类型时单独判断
          if (item.controlType == '19') {
            injections.push({
              key: item.key + '_start',
              value: moment(item.value[0]).format('yyyy-MM-DD HH:mm:ss') || ''
            })
            injections.push({
              key: item.key + '_end',
              value: moment(item.value[1]).format('yyyy-MM-DD HH:mm:ss') || ''
            })
          } else {
            injections.push({
              key: item.key,
              value: item.value
            })
          }

        }
      })
      this.requestParam.injections = injections
      this.requestParam.page = 1
      this.getCheckTplData()
    },
    // 获取自定义报表详情
    getCustomTableDetail () {
      CustomTableApi.getCustomTableDetail({
        params: {
          custom_report_id: this.id
        }
      }).then(res => {
        let tableData = res.data.field_data

        let list = []
        this.filterParamList = []
        tableData.map((item) => {
          item.label = item.ais ? item.ais : item.value
          if (item.show) {
            list.push(item)
          }
          if (item.isFilterParam === '1') {
            let componentType = this.componentTypeMap[item.control_type]
            // console.log(item, componentType, '999')
            // 判断当前字段能否作为筛选条件
            if (componentType) {
              let param = {
                label: item.label,
                index: item.filterParamIndex,
                controlType: item.control_type,
                compType: componentType,
                key: item.field,
                optionList: item.box_list || [],
                value: ''
              }
              // 时间控件判断时间格式
              if (item.control_type == '19') {
                item.control_cfg = item.control_cfg || {}
                param.date_format = this.dateFormat[item.control_cfg.date_fmt]
                param.date_type = this.dateType[item.control_cfg.date_fmt || '4']
              }
              this.filterParamList.push(param)
            }
          }
        })
        this.filterParamList.sort((a, b) => {
          return a.index - b.index
        })
        console.log(this.filterParamList, '111')
        if (res.data.sort_field) {
          this.requestParam.orders = []
          this.requestParam.orders.push({
            key: res.data.sort_field,
            value: res.data.sort_type
          })
        }
        this.customTableDetail = res.data
        this.tableData = list

        this.requestParam.check_tpl_id = res.data.check_tpl_id
        this.requestParam.project_id = this.choosedProject.project_id
        this.getCheckTplData()
      })
    },
    // 获取小程序详情数据
    getCheckTplData () {
      CustomTableApi.getCheckTplData({
        data: this.requestParam
      }).then(res => {
        if (res.code === 0) {
          let list = res.data.list
          if (list.length > 0) {
            this.showGcyRzResult = list[0].filter((item) => {
              return item.control_cfg.gcyRzResult
            }).length > 0

            let tableDataValue = []
            this.statStr = res.data.stat_str
            list.map((formItem) => {
              let temp = {}
              formItem.forEach((item) => {
                if (item.control_cfg.gcyRzResult) {
                  temp.gcyRzResult = item.control_cfg.gcyRzResult
                }
                temp[item.field] = item.field_value
              })
              tableDataValue.push(temp)
            })
            this.tableDataValue = {
              list: tableDataValue,
              total_count: res.data.total_count
            }
          } else {
            this.statStr = ''
            this.tableDataValue = {
              list: [],
              total_count: 0
            }
          }

        }
      })
    },
    gcyRzResultClick (row) {
      if (!row.length) {
        this.$message({
          message: '暂未认证',
          type: 'warning'
        })
        return
      }
      const { first, second } = row[0]
      window.open(`https://tdh.sucsoft.com.cn/#/main?${second}&channelName=${first}`, '_blank')
      console.log(row, 'row')
    }
  },
  created () {
    let store = this.$store.state.choosedProject
    let local = window.localStorage.getItem('choosedProject') || '{}'
    if (local === 'undefined' || local === '') {
      local = '{}'
    }
    let userInfoLocal = window.localStorage.userInfo || '{}'
    this.userInfo = JSON.parse(userInfoLocal)
    this.choosedProject = store.project_id ? store : JSON.parse(local)
    this.id = this.$route.query.id
    this.projectId = this.choosedProject.project_id

    this.requestParam.project_id = this.choosedProject.project_id
    let chooseList = window.localStorage.getItem('choosedProjectList') || '[]'
    this.selectedProArr = JSON.parse(chooseList)

    // this.id = '60b5e0b8f96fdd11e340d6e2'
    this.getCustomTableDetail()
  },
  mounted () {
  }
}
</script>
<style scoped lang='scss'>
.custom-table-container {
  padding: 20px;
  .el-row {
    &:first-child {
      margin-bottom: 20px;
    }
  }
  .el-input,
  .el-select,
  .el-date-editor {
    width: 100%;
  }

  .el-pagination {
    margin-top: 20px;
  }

  .stat-str {
    background-color: rgba($color: #1890ff, $alpha: 0.3);
    height: 40px;
    line-height: 40px;
    margin-bottom: 10px;
    padding-left: 20px;
    font-weight: bold;
  }

  .export-btn {
    margin-bottom: 20px;
  }
}

.gcyRzResult {
  color: #409eff;
  cursor: pointer;
}
</style>

